'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { DashboardLayout } from '@/components/layout/dashboard-layout';

export default function TestWalletPage() {
  const [status, setStatus] = useState<string[]>([]);
  
  const addStatus = (message: string) => {
    setStatus(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`]);
    console.log(message);
  };

  const testBasicConnection = async () => {
    addStatus('Starting basic connection test...');
    
    if (!window.ethereum) {
      addStatus('❌ No window.ethereum found');
      return;
    }
    
    addStatus('✅ window.ethereum exists');
    addStatus(`Provider: ${window.ethereum.constructor.name}`);
    
    try {
      addStatus('Calling eth_requestAccounts...');
      addStatus('⏳ Please check MetaMask popup and click "Connect"');
      
      const accounts = await window.ethereum.request({ 
        method: 'eth_requestAccounts' 
      });
      
      addStatus(`✅ Success! Accounts received: ${accounts.join(', ')}`);
      addStatus(`Connected with account: ${accounts[0]}`);
      
      // Check if it's the admin account
      const adminAccount = '0x44FAFD20C06299DAdF4dB652D6abA64EEbB0bdD6';
      if (accounts[0].toLowerCase() === adminAccount.toLowerCase()) {
        addStatus('✅ This is the admin account!');
      } else {
        addStatus(`⚠️ Connected account is not the admin account`);
        addStatus(`Admin account should be: ${adminAccount}`);
      }
    } catch (error: any) {
      if (error.code === 4001) {
        addStatus('❌ User rejected the connection request');
        addStatus('Please click "Connect" in MetaMask, not "Cancel"');
      } else if (error.code === -32002) {
        addStatus('⚠️ MetaMask is already processing a request');
        addStatus('Please check MetaMask for any pending requests');
      } else {
        addStatus(`❌ Error: ${error.message || error}`);
        addStatus(`Error code: ${error.code}`);
        addStatus(`Error data: ${JSON.stringify(error.data)}`);
      }
    }
  };

  const checkCurrentAccounts = async () => {
    addStatus('Checking current accounts...');
    
    if (!window.ethereum) {
      addStatus('❌ No window.ethereum found');
      return;
    }
    
    try {
      const accounts = await window.ethereum.request({ 
        method: 'eth_accounts' 
      });
      addStatus(`Current accounts: ${accounts.length > 0 ? accounts.join(', ') : 'None'}`);
    } catch (error: any) {
      addStatus(`❌ Error: ${error.message || error}`);
    }
  };

  const checkChainId = async () => {
    addStatus('Checking chain ID...');
    
    if (!window.ethereum) {
      addStatus('❌ No window.ethereum found');
      return;
    }
    
    try {
      const chainId = await window.ethereum.request({ 
        method: 'eth_chainId' 
      });
      addStatus(`Current chain ID: ${chainId} (${parseInt(chainId, 16)})`);
    } catch (error: any) {
      addStatus(`❌ Error: ${error.message || error}`);
    }
  };

  const checkPermissions = async () => {
    addStatus('Checking wallet permissions...');
    
    if (!window.ethereum) {
      addStatus('❌ No window.ethereum found');
      return;
    }
    
    try {
      // Check if we have any permissions
      if (window.ethereum._metamask && window.ethereum._metamask.isUnlocked) {
        const isUnlocked = await window.ethereum._metamask.isUnlocked();
        addStatus(`MetaMask unlocked: ${isUnlocked}`);
      }
      
      // Try to get permissions
      if (window.ethereum.request) {
        try {
          const permissions = await window.ethereum.request({
            method: 'wallet_getPermissions',
          });
          addStatus(`Current permissions: ${JSON.stringify(permissions)}`);
        } catch (e) {
          addStatus('No permissions API available');
        }
      }
    } catch (error: any) {
      addStatus(`❌ Error: ${error.message || error}`);
    }
  };

  return (
    <DashboardLayout>
      <div className="space-y-6">
        <h1 className="text-3xl font-bold">Wallet Connection Test</h1>
        
        <div className="flex gap-4">
          <Button onClick={testBasicConnection}>
            Test Basic Connection
          </Button>
          <Button onClick={checkCurrentAccounts} variant="outline">
            Check Current Accounts
          </Button>
          <Button onClick={checkChainId} variant="outline">
            Check Chain ID
          </Button>
          <Button onClick={checkPermissions} variant="outline">
            Check Permissions
          </Button>
          <Button 
            onClick={() => setStatus([])} 
            variant="outline"
          >
            Clear Log
          </Button>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>Status Log</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-1 font-mono text-sm">
              {status.length === 0 ? (
                <p className="text-gray-500">No logs yet. Click a button to start testing.</p>
              ) : (
                status.map((line, index) => (
                  <div key={index} className="py-1">
                    {line}
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  );
}